package com.apes.framework.config.druid.stat;

import com.alibaba.druid.pool.DruidDataSourceStatLoggerAdapter;
import com.alibaba.druid.pool.DruidDataSourceStatValue;
import com.alibaba.druid.stat.JdbcSqlStatValue;
import com.apes.framework.api.SpringManager;
import com.apes.framework.util.monitor.druid.pool.DataSourceStatService;
import com.apes.framework.util.monitor.druid.sql.SqlStatService;

import java.util.ArrayList;
import java.util.List;

public class ApesDruidDataSourceStatLogger extends DruidDataSourceStatLoggerAdapter {
    private List<JdbcSqlStatValue> jdbcSqlStatValues = new ArrayList<>();
    private SqlStatService sqlStatService;
    private DataSourceStatService dataSourceStatService;

    public ApesDruidDataSourceStatLogger() {
    }

    @Override
    public void log(DruidDataSourceStatValue statValue) {
        if (SpringManager.getApplicationContext() == null) {
            jdbcSqlStatValues.addAll(statValue.getSqlList());
            return;
        }
        if (sqlStatService == null) {
            sqlStatService = SpringManager.getBean(SqlStatService.class);
        }
        if (sqlStatService == null) {
            jdbcSqlStatValues.addAll(statValue.getSqlList());
            return;
        }
        if (!jdbcSqlStatValues.isEmpty()) {
            for (JdbcSqlStatValue jdbcSqlStatValue : jdbcSqlStatValues) {
                sqlStatService.add(jdbcSqlStatValue);
            }
            jdbcSqlStatValues.clear();
        }
        for (JdbcSqlStatValue jdbcSqlStatValue : statValue.getSqlList()) {
            sqlStatService.add(jdbcSqlStatValue);
        }

        if (dataSourceStatService == null) {
            dataSourceStatService = SpringManager.getBean(DataSourceStatService.class);
        }
        dataSourceStatService.add(statValue);
    }
}

